<!-- 文档管理 -->
<template>
  <div v-if="!setAuthorityShow" class="document-container">
    <div class="left-content">
      <div v-loading="treeLoading">
        <div class="left-content-tab">
          <div :class="['tab-item', { 'active-tab': activeTab === 'manage' }]" @click="changeTab('manage')">全部文件</div>
          <span class="split-line">|</span>
          <div :class="['tab-item', { 'active-tab': activeTab === 'favorite' }]" @click="changeTab('favorite')">我的收藏</div>
          <span class="split-line">|</span>
          <div :class="['tab-item', { 'active-tab': activeTab === 'upload' }]" @click="changeTab('upload')">我的上传</div>
        </div>
        <div class="left-content-search">
          <px-input v-model="treeSearchVal" placeholder="请输入文件夹名" :prefix-icon="Search" clearable @change="getTreeData" />
        </div>
        <FolderTree
          ref="folderTreeRef"
          v-has="'ALL_DOCUMENTMANAGE_FOLDER'"
          :treeData="treeData"
          @nodeClick="clickFolderTreeNode"
          @nodeDrag="moveFolderTreeNode"
          @addNode="addNode"
          @editNode="editNode"
          @deleteNode="deleteNode"
        />
      </div>
    </div>
    <div class="right-content">
      <div class="right-top-card">
        <div class="right-content-handle-btn">
          <div class="right-content-nav">
            <span v-if="folderPath.length > 1" class="nav-back nav-back-btn" @click="backPreviewNode">返回上一级</span>
            <span v-if="folderPath.length > 1" class="nav-back"> | </span>
            <span v-if="folderPath.length < 2" class="nav-back">全部文件</span>
            <px-breadcrumb v-if="folderPath.length > 1" :separator-icon="ArrowRight">
              <px-breadcrumb-item v-for="item in folderPath" :key="item.id">{{ item.label }}</px-breadcrumb-item>
            </px-breadcrumb>
          </div>
          <div style="display: flex; align-items: center">
            <div class="right-search">
              <AdvancedSearch ref="advancedSearchRef" @search="handleAdvancedSearch" />
            </div>
            <div class="btn-group">
              <px-button v-has="'ALL_DOCUMENTMANAGE_UPLOAD'" type="primary" @click="handleUpload">上传文件</px-button>
              <px-button v-has="'ALL_DOCUMENTMANAGE_MOVE'" @click="handleBatchMove">移动</px-button>
              <px-button v-has="'ALL_DOCUMENTMANAGE_STORE'" @click="handleBatchStore">收藏</px-button>
              <px-button v-has="'ALL_DOCUMENTMANAGE_DOWNLOAD'" @click="handleBatchDownload">下载</px-button>
              <px-button v-has="'ALL_DOCUMENTMANAGE_DELETE'" @click="handleBatchDelete">删除</px-button>
            </div>
          </div>
        </div>
      </div>
      <div v-loading="tableLoading" class="table-content">
        <px-table height="calc(100vh - 310px)" :data="tableData" size="small" border class="common-table" @selection-change="tableSelect">
          <px-table-column type="selection" fixed width="55" prop="selection" align="center" />
          <px-table-column prop="name" label="文件名" min-width="180" show-overflow-tooltip>
            <template #default="scope">
              <div v-if="scope.row.isReName">
                <px-input v-model="newName" style="width: 150px" />
                <px-tooltip content="保存" placement="top">
                  <px-button link :icon="Check" class="rename-icon" @click="saveReName(scope.row)" />
                </px-tooltip>
                <px-tooltip content="取消" placement="top">
                  <px-button link :icon="Close" class="rename-icon" @click="cancelReName(scope.row)" />
                </px-tooltip>
              </div>
              <div v-else class="row-fileName">
                <!-- <FolderIcon v-if="scope.row.docType === 'F'" class="file-icon" />
                  <FileIcon v-if="scope.row.docType === 'D'" class="file-icon" /> -->
                <component :is="fileIcon(scope.row)" class="file-icon" />
                <span>{{ scope.row.name }}</span>
                <LockOnIcon v-if="scope.row.archive" class="lock-icon" />
              </div>
            </template>
          </px-table-column>
          <px-table-column prop="fileSize" label="文件大小" min-width="80" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.fileSize !== null ? formatBytes(scope.row.fileSize) : "" }}
            </template>
          </px-table-column>
          <px-table-column prop="updateByName" label="修改人" min-width="80" show-overflow-tooltip />
          <px-table-column prop="updateTime" label="修改时间" min-width="100" show-overflow-tooltip />
          <px-table-column label="操作" width="150" fixed="right" align="center">
            <template #default="scope">
              <div class="table-btn-group">
                <px-tooltip content="收藏" placement="top">
                  <px-button v-if="scope.row.favorite !== 'Y'" v-has="'ALL_DOCUMENTMANAGE_STORE'" link type="primary" @click="handleStore(scope.row)">
                    <StoreIcon />
                  </px-button>
                </px-tooltip>
                <px-tooltip content="取消收藏" placement="top">
                  <px-button
                    v-if="scope.row.favorite === 'Y'"
                    v-has="'ALL_DOCUMENTMANAGE_STORE'"
                    link
                    type="primary"
                    @click="handleCancelStore(scope.row)"
                  >
                    <CancelStoreIcon />
                  </px-button>
                </px-tooltip>
                <px-tooltip content="下载" placement="top">
                  <px-button v-has="'ALL_DOCUMENTMANAGE_DOWNLOAD'" link type="primary" @click="handleDownload(scope.row)">
                    <DownloadIcon />
                  </px-button>
                </px-tooltip>
                <px-tooltip content="删除" placement="top">
                  <px-button
                    v-if="scope.row.archive !== 'Y'"
                    v-has="'ALL_DOCUMENTMANAGE_DELETE'"
                    link
                    icon="Delete"
                    type="danger"
                    @click="handleDelete(scope.row)"
                  />
                </px-tooltip>

                <px-tooltip content="更多" placement="top">
                  <span>
                    <px-popover trigger="hover" style="padding: 0">
                      <template #reference>
                        <px-button
                          v-or="[
                            'ALL_KNOWLEDGE_DOCUMENTMANAGE_PREVIEW',
                            'ALL_DOCUMENTMANAGE_FILEDETAIL',
                            'ALL_DOCUMENTMANAGE_RENAME',
                            'ALL_DOCUMENTMANAGE_MOVE',
                            'ALL_DOCUMENTMANAGE_ARCHIVE',
                            'ALL_DOCUMENTMANAGE_CANCEL_ARCHIVE',
                            'ALL_DOCUMENTMANAGE_AUTHORITY'
                          ]"
                          link
                          type="primary"
                          style="margin-left: 16px"
                        >
                          <OtherIcon />
                        </px-button>
                      </template>
                      <ul class="more-btn-group">
                        <li v-if="scope.row.docType === 'D'" v-has="'ALL_KNOWLEDGE_DOCUMENTMANAGE_PREVIEW'" @click="handlePreview(scope.row)">
                          <PreviewIcon class="more-btn-icon" />预览
                        </li>
                        <li v-if="scope.row.docType === 'D'" v-has="'ALL_DOCUMENTMANAGE_FILEDETAIL'" @click="showFileDetail(scope.row)">
                          <FileDetailIcon class="more-btn-icon" />详情
                        </li>
                        <li v-if="scope.row.archive !== 'Y'" v-has="'ALL_DOCUMENTMANAGE_RENAME'" @click="handleReName(scope.row)">
                          <RenameIcon class="more-btn-icon" />重命名
                        </li>
                        <li v-if="scope.row.archive !== 'Y'" v-has="'ALL_DOCUMENTMANAGE_MOVE'" @click="handleMove(scope.row)">
                          <MoveIcon class="more-btn-icon" />移动
                        </li>
                        <li v-if="scope.row.archive !== 'Y'" v-has="'ALL_DOCUMENTMANAGE_ARCHIVE'" @click="handleArchive(scope.row)">
                          <PlaceFileIcon class="more-btn-icon" />归档
                        </li>
                        <li v-if="scope.row.archive === 'Y'" v-has="'ALL_DOCUMENTMANAGE_CANCEL_ARCHIVE'" @click="handleCancelArchive(scope.row)">
                          <PlaceFileIcon class="more-btn-icon" />取消归档
                        </li>
                        <li v-if="scope.row.docType === 'F'" v-has="'ALL_DOCUMENTMANAGE_AUTHORITY'" @click="setAuthority(scope.row)">
                          <AuthorityIcon class="more-btn-icon" />权限管理
                        </li>
                      </ul>
                    </px-popover>
                  </span>
                </px-tooltip>
              </div>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="pageNum"
          v-model:limit="pageSize"
          class="table-pagination"
          :total="total"
          @pagination="getTableData"
        />
      </div>
    </div>
    <!-- 移动到 -->
    <MoveTo ref="moveRef" v-model:visible="moveDialogVisible" :treeData="treeData" @moveConfirm="confirmMove" />
    <!-- 文件详情 -->
    <FileDetail v-model:visible="fileDetailVisible" :fileDetailData="fileDetailData" />
    <!-- 上传文件 -->
    <FileUpload ref="uploadRef" v-model:visible="fileUploadVisible" :folderData="currentNode" @uploadAction="fileUploadConfirm" />
  </div>
  <div v-else>
    <!-- 权限管理 -->
    <SetAuthority :rowData="rowData" :currentNode="currentNode" :folderPath="folderPath" @goBack="authorityBack" />
  </div>
</template>

<script setup>
import { defineAsyncComponent, getCurrentInstance, nextTick, onMounted, reactive, ref, toRefs } from "vue";
import { useRouter } from "vue-router";
// 组件
import AdvancedSearch from "./component/advancedSearch.vue";
import FileDetail from "./component/fileDetail.vue";
import FileUpload from "./component/fileUpload.vue";
import FolderTree from "./component/folderTree.vue";
import MoveTo from "./component/moveTo.vue";
import SetAuthority from "./component/setAuthority.vue";
// 图标
import AuthorityIcon from "@/assets/svg/knowledge/authority_icon.svg?component";
import CancelStoreIcon from "@/assets/svg/knowledge/cancel_store_icon.svg?component";
import DownloadIcon from "@/assets/svg/knowledge/download_icon.svg?component";
import FileDetailIcon from "@/assets/svg/knowledge/file_detail_icon.svg?component";
import FolderIcon from "@/assets/svg/knowledge/folder.svg?component";
import LockOnIcon from "@/assets/svg/knowledge/lockon_icon.svg?component";
import MoveIcon from "@/assets/svg/knowledge/move_icon.svg?component";
import OtherIcon from "@/assets/svg/knowledge/other_icon.svg?component";
import PlaceFileIcon from "@/assets/svg/knowledge/place_file_icon.svg?component";
import PreviewIcon from "@/assets/svg/knowledge/preview_icon.svg?component";
import RenameIcon from "@/assets/svg/knowledge/rename_icon.svg?component";
import StoreIcon from "@/assets/svg/knowledge/store_icon.svg?component";
// px-ui
import { ArrowRight, Check, Close, Search } from "@px-ui/icons-vue";
import { PxMessage, PxMessageBox } from "px-ui";
// 接口
import {
  addFolderAPI,
  archiveAPI,
  cancelArchiveAPI,
  cancelStoreAPI,
  deleteAPI,
  deleteFolderAPI,
  editFolderAPI,
  fileDetailAPI,
  loadTreeAPI,
  moveFolderAPI,
  reNameAPI,
  searchDocAPI,
  storeAPI,
  uploadFileAPI
} from "@/api/knowledge/documentManage";
import { getToken } from "@/utils/auth";
import errorCode from "@/utils/errorCode";
import { formatBytes } from "@/views/all/knowledge/utils";
import axios from "axios";

defineOptions({
  name: "ALL_DOCUMENTMANAGE"
});

const router = useRouter();

const { proxy } = getCurrentInstance();
const folderTreeRef = ref();
const tree = reactive({
  treeLoading: false,
  activeTab: "manage",
  treeSearchVal: "",
  treeData: []
});
const { treeLoading, activeTab, treeSearchVal, treeData } = toRefs(tree);

const advancedSearchRef = ref();
const uploadRef = ref();
const moveRef = ref();
const state = reactive({
  total: 0,
  pageNum: 1,
  pageSize: 20,
  tableLoading: false,
  tableData: [],
  tableSelectedData: [],
  setAuthorityShow: false,
  rowData: {}, // 当前行的数据
  moveDialogVisible: false,
  folderPath: [], // 文件夹路径
  fileDetailVisible: false,
  fileUploadVisible: false,
  currentNode: {}, // 当前选中的树节点
  allParentNode: [], // 当前节点的所有父节点
  newName: "",
  isBatchHandle: false,
  fileDetailData: {}
});
const {
  total,
  pageNum,
  pageSize,
  tableLoading,
  tableData,
  setAuthorityShow,
  rowData,
  moveDialogVisible,
  folderPath,
  fileDetailVisible,
  fileUploadVisible,
  currentNode,
  newName,
  fileDetailData
} = toRefs(state);

// 切换tab
const changeTab = tab => {
  tree.activeTab = tab;
  getTreeData();
};

onMounted(() => {
  getTreeData();
});

const fileIcon = row => {
  const imgFileType = ["png", "jpg", "jpeg", "gif", "bmp", "webp"]; // 图片类型
  const videoFileType = ["mp4", "avi", "rmvb", "mov"]; // 视频类型
  const fileType = row.name.split(".").pop().toLowerCase();
  if (row.docType === "F") {
    return FolderIcon;
  } else if (row.docType === "D" && imgFileType.includes(fileType)) {
    return defineAsyncComponent(() => import("@/assets/svg/knowledge/picture.svg?component"));
  } else if (row.docType === "D" && ["doc", "docx"].includes(fileType)) {
    return defineAsyncComponent(() => import("@/assets/svg/knowledge/word.svg?component"));
  } else if (row.docType === "D" && videoFileType.includes(fileType)) {
    return defineAsyncComponent(() => import("@/assets/svg/knowledge/viedo.svg?component"));
  } else if (row.docType === "D" && ["xls", "xlsx"].includes(fileType)) {
    return defineAsyncComponent(() => import("@/assets/svg/knowledge/excel.svg?component"));
  } else if (row.docType === "D" && ["ppt", "pptx"].includes(fileType)) {
    return defineAsyncComponent(() => import("@/assets/svg/knowledge/ppt.svg?component"));
  } else if (row.docType === "D" && ["pdf"].includes(fileType)) {
    return defineAsyncComponent(() => import("@/assets/svg/knowledge/pdf.svg?component"));
  } else if (row.docType === "D" && ["txt"].includes(fileType)) {
    return defineAsyncComponent(() => import("@/assets/svg/knowledge/text.svg?component"));
  } else {
    return defineAsyncComponent(() => import("@/assets/svg/knowledge/other.svg?component"));
  }
};

const formatNull = data => {
  return data.map(node => {
    node.label = node.name;
    if (node.children == null) {
      node.children = []; // 将children属性为null的替换为空数组
    } else {
      node.children = formatNull(node.children); // 递归处理子节点
    }
    return node;
  });
};

// const byteToMb = bytes => {
//   return (bytes / 1024 / 1024).toFixed(2);
// };

// 获取左侧文件夹树数据
// val：true, currentNode保留原来的值，
const getTreeData = async val => {
  try {
    const params = {
      type: tree.activeTab, // manage：全部文件，favorite：我的收藏，upload：我的上传
      name: tree.treeSearchVal
    };
    tree.treeLoading = true;
    const res = await loadTreeAPI(params);
    tree.treeData = formatNull([res]);
    if (!val) {
      if (tree.treeSearchVal) {
        state.currentNode = tree.treeData[0]?.children?.[0];
      } else {
        state.currentNode = tree.treeData[0];
      }
    }
    folderTreeRef.value.setCurrentKey(state.currentNode.id);
    getTableData();
  } catch (err) {
    console.log(err);
  } finally {
    tree.treeLoading = false;
  }
};

// 获取右侧表格数据
const getTableData = async () => {
  try {
    state.tableLoading = true;
    state.tableData = [];
    const params = {
      id: state.currentNode.id,
      type: tree.activeTab,
      pageNum: state.pageNum,
      pageSize: state.pageSize
    };
    const res = await searchDocAPI(params);
    state.total = res.total;
    state.tableData = res.data;
  } catch (err) {
    console.log(err);
  } finally {
    state.tableLoading = false;
  }
};

// 点击树节点
const clickFolderTreeNode = async (data, node) => {
  advancedSearchRef.value.clearInput();
  const allParentNode = folderTreeRef.value.getAllParentNode(node);
  state.allParentNode = allParentNode;
  if (allParentNode.length > 0) {
    state.folderPath = allParentNode.map(item => item.data);
    state.folderPath.push(data);
  } else {
    state.folderPath = [];
  }
  state.currentNode = data;
  getTableData();
};

// 高级搜索
const handleAdvancedSearch = async nodeId => {
  folderTreeRef.value.setCurrentKey(nodeId);
  state.currentNode = { id: nodeId };
  getTableData();
};

// 移动树节点
const moveFolderTreeNode = () => {
  getTreeData();
};

// 新增树节点
const addNode = async (parentId, name) => {
  await addFolderAPI({ parentId, name });
  PxMessage.success("新增成功");
  getTreeData(true);
};

// 编辑树节点
const editNode = async (id, name) => {
  await editFolderAPI({ id, name });
  PxMessage.success("修改成功");
  getTreeData(true);
};

// 删除树节点
const deleteNode = async id => {
  await deleteFolderAPI({ id });
  PxMessage.success("删除成功");
  getTreeData(true);
};

// 返回上一级
const backPreviewNode = () => {
  const parentId = folderTreeRef.value.getParentId(state.currentNode);
  folderTreeRef.value.setCurrentKey(parentId);
  state.folderPath.pop();
  const current = state.allParentNode.filter(item => item.data.id === parentId)[0].data;
  state.currentNode = current;
  getTableData();
};

const tableSelect = val => {
  state.tableSelectedData = val;
};

// 上传文件
const handleUpload = () => {
  state.fileUploadVisible = true;
};

// 确认上传(后端暂不支持上传多文件，先循环调接口，一个一个地上传)
const fileUploadConfirm = fileList => {
  let ajaxList = [];
  fileList.forEach(file => {
    let formData = new FormData();
    formData.append("parentId", state.currentNode.id);
    formData.append("file", file.raw);
    ajaxList.push(uploadFileAPI(formData));
  });
  Promise.all(ajaxList).then(() => {
    getTableData();
    PxMessage.success("上传成功");
    uploadRef.value.cancel();
  });
};

// 批量收藏
const handleBatchStore = async () => {
  if (state.tableSelectedData.length === 0) {
    PxMessage.error("请选择要收藏的文件夹或文件");
    return;
  }
  const params = {
    id: state.tableSelectedData.map(item => item.id)
  };
  await storeAPI(params);
  PxMessage.success("收藏成功");
  getTreeData(tree);
};

// 收藏
const handleStore = async row => {
  const params = {
    id: [row.id]
  };
  await storeAPI(params);
  PxMessage.success("收藏成功");
  getTreeData(true);
};

// 取消收藏
const handleCancelStore = async row => {
  const params = {
    id: [row.id]
  };
  await cancelStoreAPI(params);
  PxMessage.success("取消收藏成功");
  getTreeData(true);
};

// 批量下载
const handleBatchDownload = () => {
  if (state.tableSelectedData.length === 0) {
    PxMessage.error("请选择要下载的文件夹或文件");
    return;
  }
  const params = {
    id: state.tableSelectedData.map(item => item.id)
  };
  download("post", "/dms/api/v1/doc/download", params, "下载文档");
};

// 下载
const handleDownload = row => {
  const params = {
    id: [row.id]
  };
  download("post", "/dms/api/v1/doc/download", params, row.name);
};

// 验证是否为blob格式
const blobValidate = data => {
  return data.type !== "application/json";
};
// 通用导出方法
const download = (method, url, data, filename) => {
  const { VITE_API_URL: proxy_url = "/" } = import.meta.env;
  // downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", background: "rgba(0, 0, 0, 0.7)", })
  return axios({
    method,
    url: `${proxy_url}${url}`,
    data,
    headers: { Authorization: "Bearer " + getToken().accessToken || "" },
    facCode: localStorage.getItem("facCode") || "",
    responseType: "blob"
  })
    .then(async res => {
      const isBlob = blobValidate(res.data);
      if (isBlob) {
        const blob = res.data;
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onload = function (e) {
          const a = document.createElement("a");
          let fileName = filename;
          // if (res.headers["content-disposition"]) {
          //   const fileNameEncode = res.headers["content-disposition"].split("filename=")[1].split(";")[0];
          //   const name = decodeURI(fileNameEncode, "utf-8").replaceAll('"', "");
          //   if (name) {
          //     fileName = name;
          //   }
          // }
          // a.download = decodeURIComponent(fileName);
          a.download = fileName;
          a.href = e.target.result;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
        };
      } else {
        const rspObj = await blobToJson(res.data);
        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
        PxMessage({
          type: "error",
          message: errMsg
        });
      }
      // downloadLoadingInstance.close();
    })
    .catch(r => {
      console.error(r);
      PxMessage({
        type: "error",
        message: r
      });
      // downloadLoadingInstance.close();
    });
};

const blobToJson = blob => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      try {
        const json = JSON.parse(reader.result);
        resolve(json);
      } catch (e) {
        reject(new Error("JSON 解析失败:", e));
      }
    };
    reader.onerror = reject;
    reader.readAsText(blob); // 以文本形式读取
  });
};

// 批量删除
const handleBatchDelete = () => {
  if (state.tableSelectedData.length === 0) {
    PxMessage.error("请选择要删除的文件夹或文件");
    return;
  }
  const params = {
    id: state.tableSelectedData.map(item => item.id)
  };
  sureDelete(params);
};

// 删除
const handleDelete = row => {
  const params = {
    id: [row.id]
  };
  sureDelete(params);
};

const sureDelete = async params => {
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      await deleteAPI(params);
      PxMessage.success("删除成功");
      getTreeData(tree);
    })
    .catch(() => {});
};

// 批量移动
const handleBatchMove = () => {
  state.isBatchHandle = true;
  if (state.tableSelectedData.length === 0) {
    PxMessage.error("请选择要移动的文件夹或文件");
    return;
  }
  state.moveDialogVisible = true;
};

// 移动
const handleMove = row => {
  state.isBatchHandle = false;
  state.rowData = row;
  state.moveDialogVisible = true;
};

// 确定移动
const confirmMove = async targetNode => {
  const params = {
    id: state.isBatchHandle ? state.tableSelectedData.map(item => item.id) : [state.rowData.id],
    targetFolderId: targetNode
  };
  await moveFolderAPI(params);
  moveRef.value.cancel();
  PxMessage.success("移动成功");
  getTreeData(true);
};

// 归档
const handleArchive = async row => {
  const params = {
    id: row.id
  };
  await archiveAPI(params);
  PxMessage.success("归档成功");
  getTableData();
};

// 取消归档
const handleCancelArchive = async row => {
  const params = {
    id: row.id
  };
  await cancelArchiveAPI(params);
  PxMessage.success("取消归档成功");
  getTableData();
};

// 文件详情
const showFileDetail = async row => {
  state.rowData = row;
  const params = {
    id: row.id
  };
  state.fileDetailData = await fileDetailAPI(params);
  state.fileDetailVisible = true;
};

// 重命名
const handleReName = row => {
  state.rowData = row;
  state.tableData.forEach(item => {
    item.isReName = item.id === row.id;
  });
  state.newName = row.name;
};

// 重命名 保存
const saveReName = async row => {
  row.isReName = false;
  const params = {
    id: row.id,
    name: state.newName
  };
  // 改文件的接口
  if (row?.docType === "D") {
    await reNameAPI(params);
  } else {
    // 改文件夹的接口
    await editFolderAPI(params);
  }
  PxMessage.success("修改成功");
  getTableData();
};

// 重命名 取消
const cancelReName = row => {
  row.isReName = false;
  row.name = state.rowData.name;
};

// 预览
const handlePreview = row => {
  const nameAry = row.name.split(".") || [];
  const type = nameAry[nameAry?.length - 1] || "";
  // "ppt", "pptx", "docx", "xlsx",
  const allowType = ["txt", "pdf", "png", "jpg", "jpeg", "mp4"];
  if (!allowType.includes(type?.toLowerCase())) {
    PxMessage.error("暂不支持该格式文件的预览");
    return;
  }
  const path = "/fullScreen/documentManage/preview";
  const query = { id: row.id, type: type?.toLowerCase() };
  const params = { path, query };
  const { href } = router.resolve(params);
  window.open(href, "_blank");
};

// 权限管理
const setAuthority = row => {
  state.rowData = row;
  state.setAuthorityShow = true;
};

// 权限管理返回
const authorityBack = () => {
  state.setAuthorityShow = false;
  nextTick(() => {
    folderTreeRef.value.setCurrentKey(state.currentNode.id);
  });
  getTableData();
};
</script>

<style lang="scss" scoped>
.document-container {
  position: relative;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  width: 100%;
  height: calc(100vh - 133px);
  border-radius: 8px;

  .left-content {
    width: 316px;
    height: 100%;
    padding: 15px 20px 20px;
    background: #fff;
    border-radius: 4px;

    .left-content-tab {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 38px;
      line-height: 38px;
      border-bottom: 1px solid #dfdfdf;

      .tab-item {
        height: 100%;
        cursor: pointer;

        &:hover {
          color: #3b82f6;
        }
      }

      .active-tab {
        border-bottom: 3px solid #3b82f6;
      }

      .split-line {
        font-size: 12px;
        color: #dfdfdf;
      }
    }

    .left-content-search {
      margin: 16px 0;
    }

    .tree-container {
      height: calc(100vh - 270px);
      overflow: auto;
    }
  }

  .right-content {
    width: calc(100% - 316px);
    height: 100%;
    padding-left: 8px;

    .right-top-card {
      padding: 16px;
      margin-bottom: 8px;
      background: #fff;
      border-radius: 4px;
    }

    .right-content-nav {
      display: flex;
      align-items: center;

      .nav-back {
        display: inline-block;
        margin-right: 4px;
        color: rgb(0 0 0 / 20%);
      }

      .nav-back-btn {
        color: #000;
        cursor: pointer;

        &:hover {
          color: #3b82f6;
        }
      }
    }

    .right-content-handle-btn,
    .btn-group,
    .right-search {
      display: flex;
      align-items: center;
    }

    .right-search {
      margin: 0 8px;
    }

    .right-content-handle-btn {
      justify-content: space-between;
      // margin: 18px 0 8px;
    }

    .search-btn {
      margin-left: 8px;
    }

    .table-content {
      padding: 15px 20px 20px;
      background: #fff;
      border-radius: 4px;
    }
  }

  .rename-icon {
    margin-left: 8px;
    color: #3b82f6;
  }

  .row-fileName {
    display: flex;
    align-items: center;

    .file-icon {
      margin-right: 4px;
    }

    .lock-icon {
      margin-left: 4px;
    }
  }
}

.more-btn-group {
  padding: 0;

  li {
    display: flex;
    align-items: center;
    height: 32px;
    margin: 4px 0;
    cursor: pointer;

    &:hover {
      color: #3b82f6;
      background: #ebf2fe;
    }

    .more-btn-icon {
      margin-right: 8px;
    }
  }
}

.move-tree-container {
  width: 316px;
  height: 500px;
  overflow: auto;
}

:deep(.px-popover.px-popper) {
  padding: 0 !important;
}

.table-btn-group {
  display: flex;
  align-items: center;
  width: 100%;
}

:deep(.px-button + .px-button) {
  margin-left: 8px;
}
</style>
